package rwi.informationsystem.client.impl;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.Socket;
import java.net.URL;

import rwi.informationsystem.core.interfaces.Client.IVehicleClient;
import rwi.informationsystem.core.variables.RwiCommunication;

public class Client implements IVehicleClient {

	private String servletpath = "http://localhost:8080/"+RwiCommunication.OBJECT_SERVLET;
	protected void shutdown() {
		System.out.println("closed");
	}

	protected void startup() {
		System.out.println("Client started.");
	}

	@Override
	public int register(int type, int posX, int posY) {
		String adress = servletpath + "?action="
				+ RwiCommunication.ACTION_REGISTER + "&"
				+ RwiCommunication.PARAMETER_POSX + "=" + posX + "&"
				+ RwiCommunication.PARAMETER_POSY + "=" + posY + "&"
				+ RwiCommunication.PARAMETER_TYPE + "=" + type;
		return Integer.parseInt(sendRequest(adress));
	}

	@Override
	public void updatePos(int id, int posX, int posY) {
		String adress = servletpath + "?action="
				+ RwiCommunication.ACTION_UPDATE_POSITION + "&"
				+ RwiCommunication.PARAMETER_ID + "=" + id + "&"
				+ RwiCommunication.PARAMETER_POSX + "=" + posX + "&"
				+ RwiCommunication.PARAMETER_POSY + "=" + posY;
		System.out.println(sendRequest(adress));
	}

	@Override
	public void unregister(int id) {
		String adress = servletpath + "?action="
				+ RwiCommunication.ACTION_UNREGISTER + "&"
				+ RwiCommunication.PARAMETER_ID + "=" + id;
		System.out.println(sendRequest(adress));
	}

	private String sendRequest(String adress) {
		URL url;
		try {
			url = new URL(adress);
			InputStream is = url.openStream();
			InputStreamReader r = new InputStreamReader(is);
			BufferedReader reader = new BufferedReader(r);
			String s = reader.readLine();
			System.out.println(s);
			return s;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "error";
	}

	@Override
	public void getRouteToPos(int id, int targetposX, int targetposY) {
		String adress = servletpath + "?action="
				+ RwiCommunication.ACTION_GET_ROUTE + "&"
				+ RwiCommunication.PARAMETER_POSX + "=" + targetposX + "&"
				+ RwiCommunication.PARAMETER_POSY + "=" + targetposY;
		System.out.println(sendRequest(adress));
	}

}
